/////////////////////////////////////////////
/// Implementation of the simple template "Tell me * of *"
/////////////////////////////////////////////

// fetching the log
log = context.getLog();

attributeMatch = context.getMatch(1);
subjectMatch = context.getMatch(2);


//first query for the attributes that could match
attributeList = queryAttributes(attributeMatch);

switch(attributeList.size()){

	case 0 : 
		//none nothing more to do
		context.sendMessage("Sorry, no attributes for$attributeMatch found");	
		break;
		
	case 1..5:
		//reasonable amount found, querying for values
		resultSetList = queryValues(subjectMatch, attributeList);
		displayResults(resultSetList);
		break;
		
	default : 
		//too many attributes found
		context.sendMessageToUser("To many attributes found, please be more specific. Found ${attributeList.each()} ");
		break;
}



//here the query for the attributes is defined
def queryAttributes (attibuteMatch){
	attributeQuery = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>  PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT DISTINCT ?z WHERE  {?z a rdf:Property . ?z rdfs:label ?label . FILTER( regex(?label , '.*"+attibuteMatch+".*','i'))}";
	def attributeList = [];
	context.queryLocally(attributeQuery).each(){res->
		res.resultRows.each(){prop->
			attributeList.add(prop["z"]);
		}
	}
	attributeList;
}

//construct the value query
def queryValues(subjectMatch, attributes){
	subjectQuery = "PREFIX foaf: <http://xmlns.com/foaf/0.1/>  SELECT DISTINCT ?value ?name ?firstname ?familyname ?s  WHERE {" 
	attributes.eachWithIndex(){attribute,i->
		if(i!=0){
			subjectQuery += " UNION ";
		}
		subjectQuery += "{?s ?p1 ?subjectpattern. ?s <"+attribute+ "> ?value . FILTER regex(?subjectpattern, '.*" + subjectMatch+".*', 'i').  OPTIONAL {?s foaf:name ?name}. OPTIONAL {?s foaf:firstName ?firstname}. OPTIONAL { ?s foaf:surname ?familyname}} ";
	}
	subjectQuery += " }";
	context.queryForTable(subjectQuery,true,null,null)
}


//display the result
def displayResults(resultSetList){
	counter = 0;
	resultSetList.each(){p2pResult->
		p2pResult.each(){res->
			if (res.getResultCount() > 0) {
				context.sendMessageToUser("From store " + res.getStoreName() + ":")
				resRows = res.getResultRows();
				log.info(resRows);
				log.info(resRows.class);
				
				for(row in resRows){
					log.info(row["value"]);
					context.sendMessageToUser(" * "+row["value"] + " (" + row["name"] + ")")
					counter++;
				}
				
				
				
				
					
			}
		}
	}		
	if(counter == 0) {
		context.sendMessageToUser("Sorry, I found no " + attributeList +" related to " + subjectMatch);
	}
}